package characters

import (
	"fmt"
	"math/rand"
	"sync"
	"time"
)

// DefaultCharacterManager 默认角色管理器实现
type DefaultCharacterManager struct {
	characters      map[string]*CharacterPersonality
	currentCharacter *CharacterPersonality
	config          *CharacterConfig
	mutex           sync.RWMutex
	rand            *rand.Rand
}

// NewCharacterManager 创建新的角色管理器
func NewCharacterManager() CharacterManager {
	return &DefaultCharacterManager{
		characters: make(map[string]*CharacterPersonality),
		config: &CharacterConfig{
			DefaultCharacterID: "huiliyi",
			EnablePersonality:  true,
		},
		rand: rand.New(rand.NewSource(time.Now().UnixNano())),
	}
}

// RegisterCharacter 注册角色
func (m *DefaultCharacterManager) RegisterCharacter(character *CharacterPersonality) error {
	if character == nil {
		return fmt.Errorf("角色不能为空")
	}
	
	if character.ID == "" {
		return fmt.Errorf("角色ID不能为空")
	}
	
	if character.Name == "" {
		return fmt.Errorf("角色名称不能为空")
	}
	
	m.mutex.Lock()
	defer m.mutex.Unlock()
	
	m.characters[character.ID] = character
	
	// 如果是第一个角色或者是默认角色，设置为当前角色
	if m.currentCharacter == nil || character.ID == m.config.DefaultCharacterID {
		m.currentCharacter = character
	}
	
	return nil
}

// GetCharacter 获取角色
func (m *DefaultCharacterManager) GetCharacter(id string) (*CharacterPersonality, error) {
	m.mutex.RLock()
	defer m.mutex.RUnlock()
	
	character, exists := m.characters[id]
	if !exists {
		return nil, fmt.Errorf("角色 %s 不存在", id)
	}
	
	return character, nil
}

// GetAllCharacters 获取所有角色
func (m *DefaultCharacterManager) GetAllCharacters() []*CharacterPersonality {
	m.mutex.RLock()
	defer m.mutex.RUnlock()
	
	characters := make([]*CharacterPersonality, 0, len(m.characters))
	for _, character := range m.characters {
		characters = append(characters, character)
	}
	
	return characters
}

// SetCurrentCharacter 设置当前角色
func (m *DefaultCharacterManager) SetCurrentCharacter(id string) error {
	character, err := m.GetCharacter(id)
	if err != nil {
		return err
	}
	
	m.mutex.Lock()
	defer m.mutex.Unlock()
	
	m.currentCharacter = character
	return nil
}

// GetCurrentCharacter 获取当前角色
func (m *DefaultCharacterManager) GetCurrentCharacter() *CharacterPersonality {
	m.mutex.RLock()
	defer m.mutex.RUnlock()
	
	return m.currentCharacter
}

// GetGreeting 获取问候语
func (m *DefaultCharacterManager) GetGreeting() string {
	character := m.GetCurrentCharacter()
	if character == nil || !m.config.EnablePersonality {
		return "您好！我是 Loomi 2.0 的智能助手。"
	}
	
	if len(character.Greetings) == 0 {
		return fmt.Sprintf("您好！我是%s %s", character.Emoji, character.Name)
	}
	
	// 随机选择一个问候语
	index := m.rand.Intn(len(character.Greetings))
	return character.Greetings[index]
}

// GetResponse 获取特定类型的响应
func (m *DefaultCharacterManager) GetResponse(responseType string) string {
	character := m.GetCurrentCharacter()
	if character == nil || !m.config.EnablePersonality {
		return m.getDefaultResponse(responseType)
	}
	
	responses, exists := character.Responses[responseType]
	if !exists || len(responses) == 0 {
		return m.getDefaultResponse(responseType)
	}
	
	// 随机选择一个响应
	index := m.rand.Intn(len(responses))
	return responses[index]
}

// GetSpecificResponse 获取当前角色的特定类型响应
func (m *DefaultCharacterManager) GetSpecificResponse(responseType string) string {
	m.mutex.RLock()
	defer m.mutex.RUnlock()
	
	if m.currentCharacter == nil {
		return ""
	}
	
	// 根据响应类型返回相应的回复
	switch responseType {
	case "hello":
		if len(m.currentCharacter.Responses["hello"]) > 0 {
			// 随机选择一个回复
			return m.currentCharacter.Responses["hello"][0]
		}
	case "thanks":
		if len(m.currentCharacter.Responses["thanks"]) > 0 {
			return m.currentCharacter.Responses["thanks"][0]
		}
	case "tired":
		if len(m.currentCharacter.Responses["tired"]) > 0 {
			return m.currentCharacter.Responses["tired"][0]
		}
	case "goodbye":
		if len(m.currentCharacter.Responses["goodbye"]) > 0 {
			return m.currentCharacter.Responses["goodbye"][0]
		}
	case "confused":
		if len(m.currentCharacter.Responses["confused"]) > 0 {
			return m.currentCharacter.Responses["confused"][0]
		}
	case "angry":
		if len(m.currentCharacter.Responses["angry"]) > 0 {
			return m.currentCharacter.Responses["angry"][0]
		}
	case "happy":
		if len(m.currentCharacter.Responses["happy"]) > 0 {
			return m.currentCharacter.Responses["happy"][0]
		}
	case "sad":
		if len(m.currentCharacter.Responses["sad"]) > 0 {
			return m.currentCharacter.Responses["sad"][0]
		}
	}
	
	return ""
}

// getDefaultResponse 获取默认响应
func (m *DefaultCharacterManager) getDefaultResponse(responseType string) string {
	switch responseType {
	case ResponseTypeHello:
		return "您好！很高兴为您服务！"
	case ResponseTypeThanks:
		return "不用客气，这是我应该做的！"
	case ResponseTypeTired:
		return "您辛苦了，要注意休息哦！"
	default:
		return "我明白了，有什么其他需要帮助的吗？"
	}
}

// GeneratePersonalizedPrompt 生成个性化提示词
func (m *DefaultCharacterManager) GeneratePersonalizedPrompt(basePrompt string) string {
	character := m.GetCurrentCharacter()
	if character == nil || !m.config.EnablePersonality {
		return basePrompt
	}
	
	personalityPrompt := fmt.Sprintf(`
你现在要扮演一个名为"%s"的角色，角色描述：%s

角色特点：
- 使用角色专属的语言风格和表达方式
- 保持角色的个性特征
- 在回答中体现角色的性格特点

请以这个角色的身份来回应用户，同时完成以下任务：

%s

记住：始终保持角色的个性，让用户感受到与真实角色对话的体验。`, 
		character.Name, character.Description, basePrompt)
	
	return personalityPrompt
}

// SetConfig 设置配置
func (m *DefaultCharacterManager) SetConfig(config *CharacterConfig) {
	m.mutex.Lock()
	defer m.mutex.Unlock()
	
	if config != nil {
		m.config = config
	}
}

// GetConfig 获取配置
func (m *DefaultCharacterManager) GetConfig() *CharacterConfig {
	m.mutex.RLock()
	defer m.mutex.RUnlock()
	
	return m.config
}